package kr.ac.postech.marathon.client.pages;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.VerticalPanel;

import kr.ac.postech.marathon.client.RegistrationService;
import kr.ac.postech.marathon.client.RegistrationServiceAsync;
import kr.ac.postech.marathon.client.models.Registration;
import kr.ac.postech.marathon.client.widgets.RegistrationForm;

/**
 * This class will contains the registration form and the agreement which 
 * is read from datastore. If the user does not agreed with the agreement,
 * it will not perform the registration.
 * 
 * @author bbirec
 *
 */
public class RegistrationPage extends Composite {
	
	private VerticalPanel vPanel;
	
	private final RegistrationServiceAsync registrationService = GWT
	.create(RegistrationService.class);
	
	
	public static class Agreement extends Composite {
		
		private RadioButton agreeButton;
		private RadioButton notAgreeButton;
		
		public Agreement() {
			VerticalPanel v = new VerticalPanel();
			
			v.add(new HTML("this is the agreement"));
			
			HorizontalPanel controls = new HorizontalPanel();
			agreeButton = new RadioButton("agreement", "동의함");
			notAgreeButton = new RadioButton("agreement", "동의하지 않음");
			notAgreeButton.setValue(true);
			controls.add(agreeButton);
			controls.add(notAgreeButton);
			
			v.add(controls);
			
			initWidget(v);
		}
		
		public boolean isAgreed() {
			return agreeButton.getValue();
		}

	}
	
	private Agreement agreement;
	private RegistrationForm registrationForm;
	
	public RegistrationPage() {
		vPanel = new VerticalPanel();
		
		// Agreement
		agreement = new Agreement();
		vPanel.add(agreement);
		
		// Information
		vPanel.add(new Label("<신청서>"));
		
		registrationForm = new RegistrationForm(); 
		vPanel.add(registrationForm);
		
		vPanel.add(new Button("등록", new ClickHandler() {

			public void onClick(ClickEvent event) {
				// Validating the input values
				if(agreement.isAgreed() == false){
					Window.alert("Must agree with");
					return;
				}
				
				
				// Submit the values to the server by RPC
				Registration r = registrationForm.getModel();
				
				registrationService.register(r, new AsyncCallback<String>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}

					public void onSuccess(String result) {
						// TODO Auto-generated method stub
						Window.alert(result);
					}
					
				});
				
				
			}
			
		}));
		
		initWidget(vPanel);
	}
}
